package jmx;

import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author Administrator
 */
public class JMX {

    public static Map<String, Object> getMetrics(String address) throws MalformedObjectNameException {


        MBeanServerConnection mbsc = createMBeanServer("localhost", "7199");
        ObjectName os = new ObjectName("java.lang:type=OperatingSystem");

        File file = new File(address);
        jmx.ReadXMLByDom4j readXML = new jmx.ReadXMLByDom4j();
        //得到帶查詢的指標信息
        List<jmx.Metric> metricList = readXML.getMetrics(file);

        Map<String, Object> map = new HashMap<String, Object>();
        for (jmx.Metric metric : metricList) {
            String mbean = metric.getMbean();

            ObjectName objName = new ObjectName(mbean);
            String name = metric.getName();

            String value = metric.getValue();
            map.put(name, getAttributes(mbsc, objName, value));
        }
        return map;
    }

    //建立rmi连接
    public static MBeanServerConnection createMBeanServer(String ip, String jmxport) {
        try {
            String jmxURL = "service:jmx:rmi:///jndi/rmi://" + ip + ":" + jmxport + "/jmxrmi";
            JMXServiceURL serviceURL = new JMXServiceURL(jmxURL);
            JMXConnector connector = JMXConnectorFactory.connect(serviceURL);
            return connector.getMBeanServerConnection();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(ip + ":" + jmxport + "连接失败");
        }

        return null;
    }

    /**
     * 使用MBeanServer获取对象名为[objName]的MBean的[objAttr]属性值
     * 静态代码: return MBeanServer.getAttribute(ObjectName name, String attribute)
     */

    private static Object getAttributes(MBeanServerConnection mbeanServer,
                                        ObjectName objName, String objAttr) {
        if (mbeanServer == null || objName == null || objAttr == null) {
            throw new IllegalArgumentException();
        }
        try {
            return mbeanServer.getAttribute(objName, objAttr);
        } catch (Exception e) {
            return null;
        }
    }

}
